<template>
  <div>
    <f-table
      ref="tableRef"
      @register="register">
      <template #header-left>
        <el-button
          v-permission:1001="$route.meta.auth"
          type="primary"
          @click="handleAdd"
          >{{ t("add") }}</el-button
        >
        <el-button
          v-permission:1002="$route.meta.auth"
          @click="handleCopyBatch()"
          >{{ t("copyBatch") }}</el-button
        >
        <el-button
          v-permission:1003="$route.meta.auth"
          @click="handleBatchDelete"
          >{{ t("deleteBatch") }}</el-button
        >
        <el-button
          v-permission:1004="$route.meta.auth"
          @click="handleStatusChangeBatch"
          >批量修改状态</el-button
        >
      </template>
      <template #statistics="scope">
        <div class="text_statistics">
          <p>观看人数：<span class="text-[red]">{{ scope.row.guankan_num||0 }}</span> 人</p>
          <p>
            {{ t("table.dati_num")
            }}<span class="text-[red]">{{ scope.row.dati_num || 0 }}</span>
            {{ t("table.dati_num.unit") }}
          </p>
          <p>
            {{ t("table.hongbao_num")
            }}<span class="text-[red]">{{ scope.row.hongbao_num || 0 }}</span>
            {{ t("table.hongbao_num.unit") }}
          </p>
          <p>
            {{ t("table.hongbao_money")
            }}<span class="text-[red]">{{ scope.row.hongbao_money || 0 }}</span>
            {{ t("table.hongbao_money.unit") }}
          </p>
          <p>
            {{ t("table.xuefen_num")
            }}<span class="text-[red]">{{ scope.row.xuefen_num || 0 }}</span>
            {{ t("table.xuefen_num.unit") }}
          </p>
        </div>
      </template>
      <template #status="scope">
        <el-switch
          :active-value="$convert(1, scope.row.status)"
          :inactive-value="$convert(0, scope.row.status)"
          :model-value="scope.row.status"
          @click="handleStatusChange(scope.row)" />
      </template>
      <template #sort="{ row }">
        <div
          class="edit"
          v-if="!row.is_edit_sort"
          @click="row.is_edit_sort = true">
          <span>{{ row.sort }}</span>
          <el-icon class="icon"><Edit /></el-icon>
        </div>
        <el-input
          v-else
          v-model.number="row.sort"
          size="small"
          @keyup.enter="handleSaveSort(row)"
          @blur="handleSaveSort(row)"></el-input>
      </template>

      <template #action="{ row }">
        <el-space wrap>
          <el-button
            type="primary"
            link
            @click="handleViewData(row)"
            >活动统计</el-button
          >
          <el-button
            type="primary"
            link
            @click="handleShowQrcode(row)"
            >{{ t("opt.activityLink") }}</el-button
          >
          <el-button
            v-permission:1005="$route.meta.auth"
            type="primary"
            link
            @click="handleEdit(row)"
            >{{ t("edit") }}</el-button
          >
          <el-button
            v-permission:1006="$route.meta.auth"
            type="primary"
            link
            @click="handleCopyBatch(row)"
            >{{ t("copy") }}</el-button
          >
          <el-button
            v-permission:1008="$route.meta.auth"
            type="primary"
            link
            @click="handleProblem(row)"
            >{{ t("opt.issuesList") }}</el-button
          >
          <!-- <el-button
            type="primary"
            link
            @click="handleEdit(row)"
            >{{ t("opt.commentRecord") }}</el-button
          > -->
          <el-button v-permission:1106="$route.meta.auth" type="primary" link @click="handleChat(row)">聊天记录</el-button>
          <el-button v-permission:1107="$route.meta.auth" type="primary" link @click="handleViewMonitoring(row)">直播中台</el-button>
          <el-button
            v-permission:1007="$route.meta.auth"
            type="danger"
            link
            @click="handleDelete(row)"
            >{{ t("delete") }}</el-button
          >
        </el-space>
      </template>
    </f-table>
    <f-form-model
      ref="formModelRef"
      :is="formModelName"
      v-bind="formModeProps"
      @change="() => methods.reload()"></f-form-model>
    <f-detail-drawer
      ref="detailDrawerRef"
      size="80%"
      is="ActivityDataDetail"></f-detail-drawer>
  </div>
</template>
<script lang="ts" setup>
import { computed, PropType, ref, getCurrentInstance, onMounted } from 'vue'
import { t } from '@/lang'
import { useRouter, useRoute } from 'vue-router'
import FTable, {
    BasicColumn,
    useTable
} from '@/addon/htscrm/components/f-table'
import {
    tableColumns,
    tableSearchFormItems
} from '@/addon/htscrm/data/activity.video.list'
import {
    batchDeleteActivityApi,
    batchUpdateActivityStatusApi,
    deleteActivityApi,
    editSortActivityApi,
    getActivityListApi
} from '@/addon/htscrm/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import FFormModel from '@/addon/htscrm/components/f-form-model'
import FDetailDrawer from '@/addon/htscrm/components/f-detail-drawer'

const instance = getCurrentInstance() as any
const { $convert } = instance?.appContext.config.globalProperties || {}

const route = useRoute()
const detailDrawerRef = ref()
const formModelRef = ref()
const formModelName = ref('ActivityCopyForm')
const formModeProps = computed(() => {
    return {
        showCancel: formModelName.value == 'ActivityCopyForm',
        fullscreen: formModelName.value == 'ActivityCopyForm',
        width: formModelName.value == 'ActivityCopyForm' ? 1200 : 600
    }
})

const prop = defineProps({
    searchForm: {
        type: Object as PropType<any>,
        default: () => ({ cate_id: 0 })
    },
    activeId: {
        type: String,
        required: false
    }
})

const router = useRouter()

const tableRef = ref()
const { methods, register } = useTable({
    rowKey: 'id',
    searchFromItems: tableSearchFormItems(t),
    columns: tableColumns(t) as BasicColumn<IActivityItem>[],
    beforeFetch: (opt) => {
    // 更新分页状态
        const params = JSON.parse(localStorage.getItem('videoParams') || '{}')
        paginationState.value.currentPage = opt.page || 1
        paginationState.value.pageSize = opt.limit || 10
        localStorage.removeItem('videoParams')
        return {
            page: params.page && Number(params.page) > 1 ? Number(params.page) : opt.page,
            limit: params.size && Number(params.size) > 10 ? Number(params.size) : opt.limit,
            cate_id: prop.searchForm.cate_id ? prop.searchForm.cate_id : Number(params.cate_id) || '',
            type: '1',
            title: opt.title || params.title || ''
        }
    },
    api: async (opt) => (await getActivityListApi(opt)).data
})

const paginationState = ref({
    currentPage: 1,
    pageSize: 10
})

/**
 * 保存搜索信息
 */
function handleRouter () {
    const params = {
        page: paginationState.value.currentPage,
        size: paginationState.value.pageSize,
        cate_id: prop.searchForm.cate_id,
        title: methods.getSearchInfo().title || ''
    }
    localStorage.setItem('videoParams', JSON.stringify(params))
}
/**
 * 新增
 */
function handleAdd () {
    handleRouter()
    if (prop.activeId && prop.activeId !== '0') {
        router.push('/htscrm/activity/video/add?activeId=' + prop.activeId)
    } else {
        router.push('/htscrm/activity/video/add')
    }
}
/**
 * 编辑
 */
function handleEdit (row: IActivityItem) {
    handleRouter()
    router.push({
        path: '/htscrm/activity/video/edit',
        query: {
            id: row.id
        }
    })
}

/**
 * 问题列表
 */
function handleProblem (row: IActivityItem) {
    handleRouter()
    router.push({
        path: '/htscrm/activity/problem',
        query: {
            id: row.id
        }
    })
}

/**
 * 聊天记录
 */
function handleChat (row: IActivityItem) {
    router.push({
        path: '/htscrm/activity/chat',
        query: {
            id: row.id
        }
    })
}

/**
 * 视频监控
 */
function handleViewMonitoring (row: IActivityItem) {
    window.open('/monitoring/' + row.id)
}

/**
 * @description 删除数据
 */
async function handleDelete (row: IActivityItem) {
    const action = await ElMessageBox.alert(t('deleteTips'), t('alert.title'), {
        type: 'warning',
        showCancelButton: true,
        cancelButtonText: t('alert.cancel'),
        confirmButtonText: t('alert.confirm')
    })
    if (action === 'confirm') {
        await deleteActivityApi(row.id)
        ElMessage.success(t('deleteSuccess'))
        methods.reload()
    }
}

/**
 * @description 批量删除
 */
async function handleBatchDelete () {
    const selection: IActivityItem[] = methods.getSelectionRows()
    if (selection.length == 0) {
        ElMessage.warning(t('deleteEmptyTips'))
        return
    }
    const ids = selection.map((item) => item.id)
    const action = await ElMessageBox.alert(
        t('deleteBatchTips'),
        t('alert.title'),
        {
            type: 'warning',
            showCancelButton: true,
            cancelButtonText: t('alert.cancel'),
            confirmButtonText: t('alert.confirm')
        }
    )
    if (action === 'confirm') {
        await batchDeleteActivityApi(ids)

        ElMessage.success(t('deleteSuccess'))
        // 清空选项
        methods.clearSelection()
        // 重新加载数据
        methods.reload()
    }
}

/**
 * @description 状态切换
 * @param row
 */
async function handleStatusChange (row: IActivityItem) {
    const text = ['启用', '停用'][row.status || 0]
    const action = await ElMessageBox.alert(
        `确认要"${text}""${row.title}"活动吗?`,
        '系统提示',
        {
            type: 'warning',
            showCancelButton: true,
            cancelButtonText: '取消',
            confirmButtonText: '确定'
        }
    )
    if (action === 'confirm') {
        const params = {
            status: [1, 0][row.status || 0],
            ids: [row.id]
        }
        await batchUpdateActivityStatusApi(params)
        ElMessage.success(`${text}成功`)
        row.status = [1, 0][row.status || 0]
    }
}

/**
 * @description 状态切换
 * @param row
 */
async function handleStatusChangeBatch () {
    const selection: IActivityItem[] = methods.getSelectionRows()
    if (selection.length == 0) {
        ElMessage.warning('请选择要操作的数据')
        return
    }

    try {
        ElMessageBox.confirm('确认要批量修改活动状态吗?', '系统提示', {
            type: 'warning',
            showCancelButton: true,
            cancelButtonText: '全部关闭',
            confirmButtonText: '全部开启',
            distinguishCancelAndClose: true,
            callback: async (action:any) => {
                if (action === 'close') return
                const params = {
                    status: action === 'confirm' ? 1 : 0,
                    ids: selection.map((item) => Number(item.id))
                }
                await batchUpdateActivityStatusApi(params)
                ElMessage.success('操作成功')
                methods.reload()
            }
        })
    } catch (error) {
    // const params = {
    //   status: 0,
    //   ids: selection.map((item) => Number(item.id)),
    // };
    // await batchUpdateActivityStatusApi(params);
    // ElMessage.success("操作成功");
    // methods.reload();
    }
}

/**
 * @description 批量复制
 */
function handleCopyBatch (row?: IActivityItem) {
    const selection: IActivityItem[] = row ? [row] : methods.getSelectionRows()
    if (selection.length == 0) {
        ElMessage.warning(t('copyBatchTips'))
        return
    }
    formModelName.value = 'ActivityCopyForm'
    setTimeout(() => {
        formModelRef.value.show('批量复制', selection, 1)
    }, 10)
}

function handleShowQrcode (row: IActivityItem) {
    formModelName.value = 'ActivityQrcodeForm'

    setTimeout(() => {
        formModelRef.value.show('活动链接', row)
    }, 10)
}
function handleViewData (row: IActivityItem) {
    detailDrawerRef.value.show('活动统计', row, prop.searchForm)
}

async function handleSaveSort (row: IActivityItem) {
    const params = {
        sort: row.sort,
        id: row.id
    }
    await editSortActivityApi(params)
    ElMessage.success('修改成功')
    row.is_edit_sort = false
    methods.reload()
}

function reload () {
    methods.clearSelection()
    methods.reload()
}

onMounted(() => {
    const params = JSON.parse(localStorage.getItem('videoParams') || '{}')
    if (params?.title) {
        methods.setFormData({
            title: params.title
        })
    }
    if (params?.page > 1) {
        methods.reload({
            page: params.page
        })
    }
})

defineExpose({
    reload
})
</script>

<style lang="scss" scoped>
.text_statistics{
  font-size: 12px;
  line-height: 18px;
}
:deep(.f-search) {
  background-color: var(--el-bg-color-page);
}

.edit {
  display: flex;
  align-items: center;
  cursor: pointer;
  .icon {
    display: none;
    margin-left: 10px;
  }

  &:hover .icon {
    display: inline;
  }
}
</style>
